package com.gaofans.nrpc.server.handler;

import com.gaofans.nrpc.common.context.ContextRequest;
import com.gaofans.nrpc.common.processor.RpcContext;
import com.gaofans.nrpc.server.service.ServiceBinder;
import com.gaofans.nrpc.server.service.ServiceHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author GaoFans
 */
@ChannelHandler.Sharable
public class RpcRequestHandler extends SimpleChannelInboundHandler<ContextRequest> {

    private final ServiceBinder binder;
    private final static Logger LOGGER = LoggerFactory.getLogger(RpcRequestHandler.class);

    public RpcRequestHandler(ServiceBinder binder) {
        super(true);
        this.binder = binder;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ContextRequest request) throws Exception {
        ServiceHandler handler = binder.get(request.getClassName());
        if (handler != null){
            LOGGER.debug("request{}开始处理",request.getSequenceId());
            request.executor().submit(() -> {
                try {
                    handler.handle(request,ctx.channel());
                }finally {
                    RpcContext.current().clear();
                }
            });
        }
    }
}
